package com.example.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.utils.R;
import com.example.common.entity.SiftParams;
import com.example.common.utils.Snowflake;
import com.example.common.utils.Util;
import com.example.sys.entity.Permission;
import com.example.sys.mapper.PermissionMapper;
import com.example.sys.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 罗文斌
 * @Date 2023/7/24
 * @Version 1.0.0
 */
@Service
@Slf4j
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public R getAllPermission(String params) {
        SiftParams siftParams = Util.transformParams(params, SiftParams.class);
        Page<Permission> page = new Page<>(siftParams.getCurrent(), siftParams.getSize());
        Page<Permission> permission = permissionMapper.getPermission(page, siftParams.getSiftName());
        List<Permission> records = permission.getRecords();
        for(Permission p : records) {
            StringBuffer menusBf = new StringBuffer();
            p.getMenusList().forEach(c -> {
                menusBf.append(",").append(c.getLabel());
            });
            String menuStr = String.valueOf(menusBf).replaceFirst(",", "");
            p.setMenuLabel(menuStr);
            p.setMenus(JSONObject.toJSONString((Util.formatMenus(p.getMenusList()))));
        }
        JSONObject rs = new JSONObject();
        rs.put("data", permission.getRecords());
        rs.put("total", permission.getTotal());
        return R.success(rs);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addRole(String params) {
        Permission permission = Util.transformParams(params, Permission.class);
        String[] menus = permission.getMenus().split(",");
        Permission role = permissionMapper.getRole(permission.getName());
        if(ObjectUtils.isNotEmpty(role)) {
            return R.error("当前角色已存在");
        }
        long id = Snowflake.nextId();
        permissionMapper.addRole(id, permission.getName(), permission.getLabel());
        for(String menu : menus) {
            permissionMapper.addRoleRelation(id, menu);
        }
        return R.success("添加成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateRole(String params) {
        try {
            Permission permission = Util.transformParams(params, Permission.class);
            String[] menus = permission.getMenus().split(",");
            permissionMapper.updateRole(permission.getId(), permission.getName(), permission.getLabel());
            permissionMapper.removeAllByRole(permission.getId());
            if(StringUtils.isNotBlank(permission.getMenus())) {
                for(String menu : menus) {
                    permissionMapper.addRoleRelation(permission.getId(), menu);
                }
            }
        } catch (Exception e) {
            log.error("修改失败：", e);
            return R.error("修改失败");
        }
        return R.success("修改成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R removeRole(String params) {
        try {
            Permission permission = Util.transformParams(params, Permission.class);
            permissionMapper.removeAllByRole(permission.getId());
            permissionMapper.removeRole(permission.getId());
        } catch (Exception e) {
            log.error("删除失败：", e);
            return R.error("删除失败");
        }
        return R.success("删除成功");
    }
}
